<!DOCTYPE html>
<html lang="en" xml:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>订单管理</title>
    <link rel="stylesheet" href="/layui/css/layui.css">
    <link rel="stylesheet" href="/css/custom.form.css">
</head>
<body>
<!--数据与分页-->
<div class="furnishOrder_table_div">
    <!--多条件查询-->
    <div id="searchParam">
        <div class="layui-form-item">
            <div class="layui-input-inline">
                <input type="text" id="name" class="layui-input" autocomplete="off" placeholder="合同名称">
            </div>
            <div class="layui-input-inline ">
                <button class="layui-btn" id="search">查询</button>
            </div>
        </div>
    </div>
    <!--显示数据的表格-->
    <table class="layui-hide" id="furnishOrder_table" lay-filter="furnishOrder_table"></table>
    <!--分页相关 View-->
    <div id="laypage" class="layui-laypage-btn"></div>
</div>

</body>
<script src="/layui/layui.js"></script>
<script src="/js/core.util.js"></script>
<!--新增合同按钮、批量删除 按钮-->
<script type="text/html" id="toolbar">
    <div class="layui-btn-group">
        <!--shiro:hasPermission="sys:furnishOrder:delete"-->
        <button type="button" class="layui-btn" lay-event="batchDeleted">
            <i class="layui-icon">&#xe608;</i> 批量删除
        </button>
    </div>
</script>
<!--给合同赋予角色按钮-->
<!--shiro:hasPermission="sys:furnishOrder:role:update"  shiro:hasPermission="sys:furnishOrder:update" shiro:hasPermission="sys:furnishOrder:delete" -->
<script type="text/html" id="tool">
    <a class="layui-btn layui-btn-xs" lay-event="edit">支付</a>
</script>
<script>

    layui.use(['jquery', 'form', 'table', 'laypage', 'layer', 'upload'], function () {
        const $ = layui.jquery;
        const form = layui.form;
        const table = layui.table;
        const laypage = layui.laypage
        const layer = layui.layer;
        const upload = layui.upload;

        /*分页查询条件*/
        const searchParam = {
            current: 1,
            size: 10,
            /*以下为多条件查询参数*/
            orderNumber: null,
        }

        //监听指定开关
        form.on('switch(switchTest)', function (data) {
            layer.msg('开关checked：' + (this.checked ? 'true' : 'false'), {
                offset: '6px'
            });
        });

        /**
         * 渲染上传文件组件
         */
        upload.render({
            elem: '#papers'
            , accept: 'file' // 允许上上传各种文件
            , url: '/upload'
            , done: function (res) {
                layer.msg('上传成功');
                setPapersValue(res.data.src, res.data.title)
            }
        });

        /**
         * 设置上传的文件
         * @param src 上传的文件路径
         * @param papersName 文件名
         */
        let setPapersValue = function (src, papersName) {
            if (papersName !== undefined) {
                layui.$('#uploadDemoView').find('ul').append(`<li  style="display: flex;align-content: center">${papersName}<i class="layui-icon file"></i></li>`)
                $("input[name=papersName]").val(papersName)
            }
            $("input[name=papers]").val(src)
            $(".file").on("click",function (even) {
                $("input[name=papersName]").val("")
                $("input[name=papers]").val("")
                $(even.target).parent().remove()
                layer.msg("移除成功")
                return false
            })
        }


        /**
         *  加载分页数据
         */
        function loadPageInfo() {
            CoreUtil.sendAjax("/zx/furnishOrder/page", searchParam, function (res) {
                //初始化分页器
                laypageTable(res.total, searchParam.current);
                //初始化渲染数据
                loadTable(res.records);
                if (res.records != null) {
                    loadTable(res.records);
                }
            }, "GET", false, function (res) {
                //用户列表接口无权限回调
                layer.msg("抱歉！您暂无获取用户列表的权限");
                let noAuthorityData;
                noAuthorityData = [];
                loadTable(noAuthorityData);
            });
        }


        $("#search").click(function () {
            searchParam.name = $("#name").val();
            searchParam.current = 1;
            loadPageInfo();
        });

        //渲染分页插件
        const laypageTable = function (count, currentPage) {
            laypage.render({
                elem: 'laypage'
                , count: count
                , limit: searchParam.size
                , layout: ['count', 'prev', 'page', 'next', 'limit', 'refresh', 'skip']
                , curr: location.hash.replace('#!currentPage=', '')     //获取起始页
                , hash: 'currentPage'                                   //自定义hash值
                , jump: function (obj, first) {
                    if (!first) {
                        searchParam.current = obj.curr;
                        searchParam.size = obj.limit;
                        loadPageInfo();
                    }
                }
            });
        };
        //渲染table
        const loadTable = function (data) {
            //展示已知数据
            table.render({
                elem: '#furnishOrder_table'
                // 这个 data 为数组数据，直接 放到 data 上即可。
                , data: data
                , even: true
                , limit: data.length
                , limits: [10, 20, 30, 40, 50]
                , toolbar: '#toolbar'
                , cols: [
                    [
                        {type: 'checkbox', fixed: 'left'},
                        {field: 'id', title: 'ID', width: 20, sort: true},
                        {field: 'orderNumber', title: '订单号', width: 230},
                        {field: 'orderUnitPrice', title: '订单单价', width: 230},
                        {field: 'orderSum', title: '订单总价格', width: 230},
                        {field: 'squareMeter', title: '装修面积（平米）', width: 230},
                        {field: 'status', title: '状态', width: 230,templet: generateOrderSwitch},
                        {width: 300, toolbar: "#tool", title: '操作'}
                    ]
                ]
            });
        };
        loadPageInfo();

        //点击新增事件， 表头工具栏事件
        table.on('toolbar(furnishOrder_table)', function (obj) {
            switch (obj.event) {
                case 'addNewfurnishOrder':
                    $(".title").html("新增合同");
                    $(".furnishOrder_table_div").hide();
                    $(".operation_furnishOrder").show();
                    $(".operation_furnishOrder input[name=id]").val("");
                    $(".operation_furnishOrder input[name=name]").val("");
                    // 清理文件上传信息
                    $(".operation_furnishOrder input[name=papers]").val("");
                    $(".operation_furnishOrder input[name=papersName]").val("");
                    // 签订人重置
                    $(".operation_furnishOrder input[name=signatory]").val("")
                    form.render(); //更新全部
                    break;
                case 'batchDeleted':
                    let checkStatus = table.checkStatus(obj.config.id);
                    let data = checkStatus.data;
                    if (data.length === 0) {
                        layer.msg("请选择要批量删除的合同");
                    } else {
                        let furnishOrderIds = [];
                        $(data).each(function (index, item) {
                            furnishOrderIds.push(item.id);
                        });
                        tipDialog(furnishOrderIds, "选中的");
                    }
                    break;
            }
        });

        //编辑或新增的界面取消事件
        $("#btn_cancel").click(function () {
            //显示表格
            $(".furnishOrder_table_div").show();
            //隐藏编辑窗口
            $(".operation_furnishOrder").hide();
            //可以防止在表单事件操作后自动刷新
            return false;
        });

        //监听提交 新增和编辑  保存按钮
        form.on('submit(submit)', function (data) {
            data.field.status = getStatus(data.field)
            //新增
            if (data.field.id === undefined || data.field.id === null || data.field.id === "") {
                CoreUtil.sendAjax("/zx/furnishOrder", JSON.stringify(data.field), function (res) {
                    //显示表格
                    loadPageInfo();
                    $(".furnishOrder_table_div").show();
                    //隐藏编辑窗口
                    $(".operation_furnishOrder").hide();
                    // 刷新页面，但是不管事儿
                    $(".layui-laypage-btn").click();
                }, "POST", false, function (res) {
                    //新增合同无权限提示
                    layer.msg("抱歉！您暂无新增合同的权限");
                });
                // 编辑
            } else {
                CoreUtil.sendAjax("/zx/furnishOrder", JSON.stringify(data.field), function (res) {
                    //显示表格
                    $(".furnishOrder_table_div").show();
                    //隐藏编辑窗口
                    $(".operation_furnishOrder").hide();
                    $(".layui-laypage-btn").click();
                }, "POST", false, function (res) {
                    //更新合同无权限提示
                    layer.msg("抱歉！您暂无编辑合同的权限");
                });
            }
            return false;
        });


        //执行查询
        $("#search").click(function () {
            searchParam.orderNumber = $("#name").val();
            searchParam.current = 1;
            loadPageInfo();
        });


        // 操作工具栏 点击赋予角色事件事件
        table.on('tool(furnishOrder_table)', function (obj) {
            var data = obj.data;
            switch (obj.event) {
                case 'edit':
                    CoreUtil.sendAjax(`/zx/furnishOrder/${data.id}/status`, null, null, "PUT");
                    top.window.location.href= `/ali/pay?outTradeNo=${data.orderNumber}&subject=12&totalAmount=${data.orderSum}&body=12`
                    break;
                case 'del':
                    var furnishOrderIds = [];
                    furnishOrderIds.push(data.id);
                    tipDialog(furnishOrderIds, data.name);
                    break;
            }
        });

        /**
         * 通过状态获取状态值
         */
        const getStatus = function (data) {
            let status = data.status;
            return status === 'on' ? 1 : 0;
        }

        /**
         * 设置表单中的状态
         */
        const setStatus = function (element, status) {
            if (status === 1) {
                $(element).attr("checked", "checked")
            } else {
                $(element).removeAttr("checked")
            }
        }

        /**
         * 更具状态值获取状态
         */
        const generateSwitch = function (data) {
            let status = data.status;
            return status === 1 ? "开启" : "关闭";
        }

        const generateOrderSwitch = function (data) {
            let status = data.status;
            return status === 1 ? "已支付" : "未支付";
        }

        //删除前确认对话框
        const tipDialog = function (furnishOrderIds, name) {
            layer.open({
                content: '确定要删除' + name + "合同么?",
                yes: function (index, layero) {
                    layer.close(index); //如果设定了yes回调，需进行手工关闭
                    CoreUtil.sendAjax("/zx/furnishOrder", JSON.stringify(furnishOrderIds), function (res) {
                        layer.msg(res.message);
                        $(".layui-laypage-btn").click();
                    }, "DELETE", false, function (res) {
                        //删除合同无权限
                        layer.msg("抱歉！您暂无删除合同的权限");
                    });
                }
            });
        };
    });
</script>
</html>

